import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, DatePicker, Spin, message, Typography } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined, UserOutlined, TeamOutlined } from '@ant-design/icons';
import { getAdminStats, getTrafficStats, getActiveUsersStats } from '../../api/admin';
import { formatBytes } from '../../utils/format';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Text } = Typography;

interface TrafficData {
  date: string;
  upload: number;
  download: number;
}

interface ActiveUsersData {
  date: string;
  activeUsers: number;
  newUsers: number;
}

// 后端返回的统计数据结构
interface SiteOverviewStats {
  totalUsers: number;
  totalTorrents: number;
  todayUpload: number;
  todayDownload: number;
  totalUploaded?: number;
  totalDownloaded?: number;
}

const AdminStats: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [overviewStats, setOverviewStats] = useState<SiteOverviewStats | null>(null);
  const [trafficData, setTrafficData] = useState<TrafficData[]>([]);
  const [activeUsersData, setActiveUsersData] = useState<ActiveUsersData[]>([]);
  const [dateRange, setDateRange] = useState<[Dayjs, Dayjs]>([
    dayjs().subtract(30, 'day'),
    dayjs()
  ]);

  useEffect(() => {
    loadData();
  }, []);

  useEffect(() => {
    if (dateRange) {
      const days = dateRange[1].diff(dateRange[0], 'day') + 1;
      loadTrafficData(days);
      loadActiveUsersData(days);
    }
  }, [dateRange]);

  const loadData = async () => {
    setLoading(true);
    try {
      await Promise.all([
        loadOverviewStats(),
        loadTrafficData(30),
        loadActiveUsersData(30)
      ]);
    } catch (error) {
      message.error('加载数据失败');
    } finally {
      setLoading(false);
    }
  };

  const loadOverviewStats = async () => {
    try {
      const response = await getAdminStats();
      if (response.code === 200) {
        setOverviewStats(response.data as any);
      }
    } catch (error) {
      console.error('加载概览统计失败:', error);
    }
  };

  const loadTrafficData = async (days: number) => {
    try {
      let response;
      if (dateRange && dateRange[0] && dateRange[1]) {
        const startDate = dateRange[0].format('YYYY-MM-DD');
        const endDate = dateRange[1].format('YYYY-MM-DD');
        response = await getTrafficStats(days, startDate, endDate);
      } else {
        response = await getTrafficStats(days);
      }

      if (response?.code === 200) {
        const data = response.data?.dailyStats || [];
        setTrafficData(Array.isArray(data) ? data : []);
      } else {
        console.error('流量统计API返回错误:', response?.message);
        setTrafficData([]);
      }
    } catch (error) {
      console.error('加载流量统计失败:', error);
      setTrafficData([]);
      message.error('加载流量统计失败');
    }
  };

  const loadActiveUsersData = async (days: number) => {
    try {
      let response;
      if (dateRange && dateRange[0] && dateRange[1]) {
        const startDate = dateRange[0].format('YYYY-MM-DD');
        const endDate = dateRange[1].format('YYYY-MM-DD');
        response = await getActiveUsersStats(days, startDate, endDate);
      } else {
        response = await getActiveUsersStats(days);
      }

      if (response?.code === 200) {
        const data = response.data?.activeUsers || [];
        setActiveUsersData(Array.isArray(data) ? data : []);
      } else {
        console.error('活跃用户统计API返回错误:', response?.message);
        setActiveUsersData([]);
      }
    } catch (error) {
      console.error('加载活跃用户统计失败:', error);
      setActiveUsersData([]);
      message.error('加载活跃用户统计失败');
    }
  };



  const calculateTotalTraffic = () => {
    if (!Array.isArray(trafficData) || trafficData.length === 0) {
      return { totalUpload: 0, totalDownload: 0 };
    }
    
    const totalUpload = trafficData.reduce((sum, item) => sum + (item.upload || 0), 0);
    const totalDownload = trafficData.reduce((sum, item) => sum + (item.download || 0), 0);
    return { totalUpload, totalDownload };
  };

  const calculateAverageActiveUsers = () => {
    if (!Array.isArray(activeUsersData) || activeUsersData.length === 0) return 0;
    const total = activeUsersData.reduce((sum, item) => sum + (item.activeUsers || 0), 0);
    return Math.round(total / activeUsersData.length);
  };

  const calculateTotalNewUsers = () => {
    if (!Array.isArray(activeUsersData) || activeUsersData.length === 0) return 0;
    return activeUsersData.reduce((sum, item) => sum + (item.newUsers || 0), 0);
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  const { totalUpload, totalDownload } = calculateTotalTraffic();

  return (
    <div style={{ padding: '24px' }}>
      <h2>站点统计</h2>
      
      <Card style={{ marginBottom: 16, backgroundColor: '#fafafa' }}>
        <Text type="secondary">
          <strong>数据说明：</strong>
          流量统计基于用户注册时的累计上传下载数据，按注册日期分组统计；
          活跃用户统计基于用户的实际登录时间和注册时间。
          统计数据会根据选择的时间范围实时更新。
        </Text>
      </Card>

      {/* 概览统计 */}
      {overviewStats && (
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="总用户数"
                value={overviewStats.totalUsers}
                prefix={<UserOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="种子总数"
                value={overviewStats.totalTorrents}
                prefix={<ArrowUpOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="今日上传"
                value={formatBytes(overviewStats.todayUpload || 0)}
                prefix={<ArrowUpOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="今日下载"
                value={formatBytes(overviewStats.todayDownload || 0)}
                prefix={<ArrowDownOutlined />}
              />
            </Card>
          </Col>
        </Row>
      )}

      {/* 日期范围选择 */}
      <Card style={{ marginBottom: 24 }}>
        <div style={{ marginBottom: 16 }}>
          <span style={{ marginRight: 8 }}>时间范围：</span>
          <RangePicker
            value={dateRange}
            onChange={(dates) => {
              if (dates && dates[0] && dates[1]) {
                setDateRange([dates[0], dates[1]]);
              }
            }}
            format="YYYY-MM-DD"
          />
        </div>
      </Card>

      {/* 流量统计 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Card title="流量统计" extra={<Text type="secondary" style={{fontSize: '12px'}}>基于用户注册时累计数据</Text>}>
            <Row gutter={16}>
              <Col span={12}>
                <Statistic
                  title="总上传"
                  value={formatBytes(totalUpload)}
                  prefix={<ArrowUpOutlined />}
                  valueStyle={{ color: '#3f8600' }}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="总下载"
                  value={formatBytes(totalDownload)}
                  prefix={<ArrowDownOutlined />}
                  valueStyle={{ color: '#cf1322' }}
                />
              </Col>
            </Row>
            <div style={{ marginTop: 16 }}>
              <p>统计周期内每日流量数据：</p>
              {Array.isArray(trafficData) && trafficData.length > 0 ? (
                trafficData.slice(-7).map(item => (
                  <div key={item.date} style={{ marginBottom: 8 }}>
                    <span>{item.date}: </span>
                    <span style={{ color: '#3f8600' }}>↑{formatBytes(item.upload || 0)}</span>
                    <span style={{ margin: '0 8px' }}>|</span>
                    <span style={{ color: '#cf1322' }}>↓{formatBytes(item.download || 0)}</span>
                  </div>
                ))
              ) : (
                <div style={{ color: '#999' }}>暂无数据</div>
              )}
            </div>
          </Card>
        </Col>
        <Col span={12}>
          <Card title="用户活跃度统计" extra={<Text type="secondary" style={{fontSize: '12px'}}>基于用户登录和注册时间</Text>}>
            <Row gutter={16}>
              <Col span={12}>
                <Statistic
                  title="平均活跃用户"
                  value={calculateAverageActiveUsers()}
                  prefix={<TeamOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
              </Col>
              <Col span={12}>
                <Statistic
                  title="新增用户"
                  value={calculateTotalNewUsers()}
                  prefix={<UserOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
              </Col>
            </Row>
            <div style={{ marginTop: 16 }}>
              <p>统计周期内每日活跃度数据：</p>
              {Array.isArray(activeUsersData) && activeUsersData.length > 0 ? (
                activeUsersData.slice(-7).map(item => (
                  <div key={item.date} style={{ marginBottom: 8 }}>
                    <span>{item.date}: </span>
                    <span style={{ color: '#1890ff' }}>活跃 {item.activeUsers || 0}</span>
                    <span style={{ margin: '0 8px' }}>|</span>
                    <span style={{ color: '#52c41a' }}>新增 {item.newUsers || 0}</span>
                  </div>
                ))
              ) : (
                <div style={{ color: '#999' }}>暂无数据</div>
              )}
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default AdminStats; 